package com.hwtx.form.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class JsonHierarchyFinder {

    private static class SearchResult {
        JsonNode target;
        List<JsonNode> ancestors;

        SearchResult(JsonNode target, List<JsonNode> ancestors) {
            this.target = target;
            this.ancestors = ancestors;
        }
    }

    /**
     * 查找符合条件的节点及其祖先（优化版）
     *
     * @param ancestorValues 为null时表示不限制值，空列表表示必须存在字段
     */
    public static List<SearchResult> findNodesWithAncestors(
            JsonNode root,
            String targetNodeName,
            String targetField,
            List<String> targetValues,
            String ancestorField,
            List<String> ancestorValues) {

        List<SearchResult> results = new ArrayList<>();
        traverse(root, new ArrayList<>(), targetNodeName, targetField, targetValues,
                ancestorField, ancestorValues, results);
        return results;
    }

    private static void traverse(
            JsonNode node,
            List<JsonNode> path,
            String targetName,
            String targetField,
            List<String> targetValues,
            String ancestorField,
            List<String> ancestorValues,
            List<SearchResult> results) {

        path.add(node);

        // 目标节点匹配检查
        if (isTargetNode(node, targetName, targetField, targetValues)) {
            List<JsonNode> validAncestors = Collections.emptyList();

            // 仅当需要祖先过滤时才执行
            if (ancestorField != null || ancestorValues != null) {
                validAncestors = filterAncestors(
                        path.subList(0, path.size() - 1),
                        ancestorField,
                        ancestorValues
                );
            }

            results.add(new SearchResult(node, validAncestors));
        }

        // 递归处理子节点（优化路径拷贝）
        if (node.isObject()) {
            node.fields().forEachRemaining(entry ->
                    traverse(entry.getValue(), new ArrayList<>(path),
                            targetName, targetField, targetValues,
                            ancestorField, ancestorValues, results)
            );
        } else if (node.isArray()) {
            node.forEach(element ->
                    traverse(element, new ArrayList<>(path),
                            targetName, targetField, targetValues,
                            ancestorField, ancestorValues, results)
            );
        }
    }

    // 目标节点验证（保持原逻辑不变）
    private static boolean isTargetNode(JsonNode node,
                                        String nodeName,
                                        String field,
                                        List<String> values) {
        if (!node.isObject()) return false;
        if (!node.has(nodeName)) return false;

        JsonNode target = node.get(nodeName);
        if (field == null) return true;

        JsonNode valueNode = target.get(field);
        if (valueNode == null) return false;

        return values == null || values.isEmpty() || values.contains(valueNode.asText());
    }

    // 祖先过滤（逻辑优化）
    private static List<JsonNode> filterAncestors(List<JsonNode> ancestors,
                                                  String field,
                                                  List<String> values) {
        List<JsonNode> filtered = new ArrayList<>();
        for (JsonNode ancestor : ancestors) {
            if (checkAncestor(ancestor, field, values)) {
                filtered.add(ancestor);
            }
        }
        return filtered;
    }

    // 祖先验证（支持空值逻辑）
    private static boolean checkAncestor(JsonNode node,
                                         String field,
                                         List<String> values) {
        if (field == null) return false; // 优化点：当field为null时不进行祖先匹配

        if (!node.isObject()) return false;
        JsonNode valueNode = node.get(field);
        if (valueNode == null) return false;

        return values == null || values.isEmpty() || values.contains(valueNode.asText());
    }

    public static void main(String[] args) throws Exception {
        String json = """
                                {
                  "organization": {
                    "id": "org1",
                    "departments": [
                      {
                        "department": {
                          "id": "dept1",
                          "employees": [
                            {
                              "employee": {
                                "id": "emp1",
                                "role": "developer"
                              }
                            }
                          ]
                        }
                      },
                      {
                        "department": {
                          "id": "dept2",
                          "employees": [
                            {
                              "employee": {
                                "id": "emp2",
                                "role": "developer"
                              }
                            }
                          ]
                        }
                      }
                    ]
                  }
                }""";
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(json);

        // 测试案例1：不查找祖先
        List<SearchResult> results = findNodesWithAncestors(
                root,
                "employee",    // 目标节点名称
                "role",        // 目标字段
                List.of("developer"), // 目标值
                "id",          // 祖先字段
                null           // 不限祖先值
        );
        results.forEach(res -> {
            System.out.println("目标节点: " + res.target);
            System.out.println("祖先数量: " + res.ancestors.size()); // 应为0
        });

        // 测试案例2：正常查找祖先
        List<SearchResult> results2 = findNodesWithAncestors(
                root,
                "employee", "id", List.of("E100"),
                "dept", null
        );
        results2.forEach(res -> {
            System.out.println("\n目标节点: " + res.target);
            System.out.println("符合条件的祖先:");
            res.ancestors.forEach(anc -> System.out.println(" - " + anc));
        });
    }
}